<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryRef" :inline="true" label-width="68px" v-if="showSearch">
      <el-form-item label="分类">
        <el-cascader
            :props="categoryProps"
            v-model="queryCategoryIdList"
            @change="handleCategoryChange"
            style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="规格名称">
        <el-input placeholder="请输入规格名称" v-model="queryParams.specName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="doReset()">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    按钮-->
    <el-row>
      <el-button type="primary" icon="Plus" @click="handleAdd()"
                 v-hasPermi="['product:productSpec:add']">新增</el-button>
      <el-button type="success" icon="Edit" :disabled="single" @click="handleChange()"
                 v-hasPermi="['product:productSpec:edit']">修改</el-button>
      <el-button type="danger" icon="Delete" :disabled="multiple" @click="handelDelete"
                 v-hasPermi="['product:productSpec:delete']">删除</el-button>
      <el-tooltip circle :content="showCircle" placement="top">
        <el-button icon="Search" @click="change()"></el-button>
      </el-tooltip>
      <el-button icon="Refresh" circle @click="getList"/>
    </el-row>

    <!--    表格数据-->
    <el-table :data="specList" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="categoryName" label="分类名称" width="180"/>
      <el-table-column prop="specName" label="规格名称" width="180"/>
      <el-table-column prop="address" label="规格值" #default="scope">
        <div v-for="(item1,index1) in scope.row.specValue"
             :key="index1"
             style="padding: 5px;margin: 0;width: 100%"
        >
          {{ item1.key }} :
          <span
              v-for="(item2,index2) in item1.valueList"
              :key="index2"
              class="div-atrr">
            {{ item2 }}
          </span>
        </div>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作" #default="scope">
        <el-button type="primary" link icon="Edit" @click="handleChange(scope.row)"
                   v-hasPermi="['product:productSpec:edit']">修改</el-button>
        <el-button type="primary" link icon="Delete" @click="handelDelete(scope.row)"
                   v-hasPermi="['product:productSpec:delete']">删除</el-button>
      </el-table-column>
    </el-table>

    <!--    新增或修改-->
    <el-dialog
        v-model="open"
        :title="title"
        width="500"
    >
      <el-form :model="form">
        <el-form-item label="分类" :rules="[{
        required: true,
        message:'品牌名不能为空',
        trigger: 'blur'
      }]">
          <el-cascader
              :props="categoryProps"
              v-model="form.categoryIdList"
              @change="handleCategoryChange"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="规格名称" :rules="[{
        required: true,
        message:'品牌名不能为空',
        trigger: 'blur'
      }]">
          <el-input placeholder="请输入规格名称" v-model="form.specName"></el-input>
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item1,index1) in specValueList" :key="index1" style="padding: 10px;margin-left: 20px;width:100%">
            {{ item1.key }}
            <span v-for="(item2,index2) in item1.valueList" :key="index2" class="div-atrr"
            >
              {{ item2 }}

            </span>
            <el-button style="float: right" @click="deleteSpec(index1)">删除</el-button>
          </div>
          <el-row v-if="isAdd">
            <el-col :span="10">
              <el-input placeholder="规格" style="width: 90%" v-model="specValue.key"></el-input>
            </el-col>
            <el-col :span="10">
              <el-input placeholder="规格值(如:白色,红色)" style="width: 90%" v-model="specValue.values"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button size="default" @click="addSpecValue">添加</el-button>
            </el-col>
          </el-row>
          <el-row v-if="!isAdd">
            <el-col :span="4">
              <el-button size="default" @click="add()">
                添加新规格
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reset()">取消</el-button>
          <el-button type="primary" @click="submit()">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

  </div>
</template>

<script setup>
import {ref, reactive, toRefs} from 'vue'
import {
  productSpecList,
  productSpecDelete,
  productSpecDeleteAdd,
  getSpecDetail,
  productSpecDeleteUpdate
} from '@/api/product/productSpec'
import {ElMessage, ElMessageBox} from "element-plus";
import {listCategory} from "@/api/product/categorybrand";

const showCircle = ref("隐藏搜索框")
const showSearch = ref(true)

function change() {
  if (showCircle.value == "隐藏搜索框") {
    showSearch.value = false
    showCircle.value = "显示搜索框"
  }else if(showCircle.value == "显示搜索框"){
    showSearch.value = true
    showCircle.value = "隐藏搜索框"
  }
}

//三级分类
const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  async lazyLoad(node, resolve) {
    const {level} = node
    if (typeof node.value == 'undefined') node.value = 0
    const {code, data, message} = await listCategory(
        node.value
    )
    //hasChildren判断是否有子节点
    data.forEach(function (item) {
      item.leaf = !item.hasChildren
    })
    resolve(data)
  },
}
const categoryProps = ref(props)

//处理分类change事件
const queryCategoryIdList = ref([])
const handleCategoryChange = () => {
  if (queryCategoryIdList.value.length == 3) {
    queryParams.value.categoryId = queryCategoryIdList.value[2]
  }
}
//定义查询数据
const data = reactive({
  queryParams: {
    pageNum: undefined,
    pageSize: undefined,
    specName: undefined,
    categoryId: undefined

  },
  form: {}
})
//页面总记录数
const total = ref(10)
//加载数据
const loading = ref()
const {queryParams, form} = toRefs(data)
//批量操作
const ids = ref()
const id = ref()
const multiple = ref()
const single = ref()

//重置搜索框数据
function doReset() {
  queryParams.value.specName = null
  queryParams.value.categoryId = null
  queryCategoryIdList.value = []
  getList()
}

function handleQuery() {
  getList()
}

//选择变化的函数
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  id.value = selection.map(item => item.id)
  multiple.value = !selection.length
  single.value = selection.length != 1
}

// 表格数据模型
const specList = ref([])


function getList() {

  loading.value = true
  productSpecList(queryParams.value).then(response => {
    console.log(response)
    specList.value = response.rows
    specList.value.forEach(item => {
      item.specValue = JSON.parse(item.specValue)
    })
    total.value = response.total
    loading.value = false
  })

}

//获取品牌列表

getList()

//删除
function handelDelete(row) {
  debugger
  const _id = row.id || ids.value
  ElMessageBox.confirm("确定要删除编号为:" + _id + " 商品规格吗?", {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    productSpecDelete(_id).then(response => {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      getList()
    })
  }).catch(() => {
    ElMessage('取消删除')
  })
}

//dialog对话框
const specValue = ref({
  key: '',
  values: ''
})
const specValueList = ref([])

const isAdd = ref(false)
//控制对话框是否打开
const open = ref(false)
const title = ref()
//对话框数据
const value = ref('请选择')

function addSpecValue() {
  specValueList.value.push({
    key: specValue.value.key,
    valueList: specValue.value.values.split(",")
  })
  specValue.value = {key: '', values: ''}
  isAdd.value = false
}

function deleteSpec(index) {
  specValueList.value.splice(index, 1)
}

function add() {
  isAdd.value = true
}

function submit() {
  form.value.specValue = JSON.stringify(specValueList.value)
  form.value.categoryId = form.value.categoryIdList[2]
  debugger
  if (form.value.id == null) {
    productSpecDeleteAdd(form.value).then(response => {
      ElMessage({
        type: "success",
        message: "增加成功"

      })
      open.value = false
      getList()
    })
  } else {
    productSpecDeleteUpdate(form.value).then(response => {
      ElMessage({
        type: "success",
        message: "修改成功"
      })
      open.value = false
      getList()
    })
  }

}


//重置对话框数据
function reset() {
  title.value = ""
  open.value = false
  form.value.specName = ""
  form.value.categoryId = ""
  form.value.categoryIdList = ""
  form.value.specValue = ""
  form.value.id = ""
}

function handleAdd() {
  reset()
  open.value = true
  title.value = '添加商品规格'
}

function handleChange(row) {
  reset()
  open.value = true
  title.value = '修改商品规格'
  const _id = row.id
  getSpecDetail(_id).then(response => {
    form.value.id = response.data.id
    form.value.categoryIdList = response.data.categoryIdList
    form.value.specName = response.data.specName
    specValueList.value = JSON.parse(response.data.specValue)
    console.log("这是回显详情")
    console.log(response)
    console.log(response.data)
  })

}

</script>
<style scoped>
.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}
</style>